package roma.lab1;

import java.net.MalformedURLException;
import java.net.URL;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Map;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;

import android.app.Activity;
import android.app.Application;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Adapter;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.Spinner;
import android.widget.SpinnerAdapter;
import android.widget.TextView;
import android.widget.Toast;

public class Romaandroidlab1Activity extends Activity {

	private static final int REFRESH = 0;
	private static final int SETTINGS = 1;
	private final String URLadress = "http://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml";
	private RomaHandler handler;
	private DatabaseHelper db;
	private Spinner to;
	private Spinner from;
	private TextView result;
	private ProgressBar loading;
	private SharedPreferences pref;
	private EditText edit;
	private Toast notOnlineToast;
	private Toast unableToUpdateRatesToast;
	private Toast validNumber;
	private DateFormat df;
	private SAXParserFactory spf;
	private SAXParser sp;
	private XMLReader xr;
	private AsyncTask task;
	private Handler h;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		try {
			handler = new RomaHandler();
			db = new DatabaseHelper(getApplicationContext());

			notOnlineToast = Toast.makeText(this, "you are currently offline", Toast.LENGTH_LONG);
			unableToUpdateRatesToast = Toast.makeText(this, "Unable to update currency rates.", Toast.LENGTH_LONG);
			validNumber = Toast.makeText(this, "Please enter a valid number", Toast.LENGTH_LONG);
			
			pref = getSharedPreferences("romaexchange", 0);
			df = new SimpleDateFormat("yyyy-MM-dd");
			
			// Component bind.
			to = (Spinner) findViewById(R.id.toSpinner);
			from = (Spinner) findViewById(R.id.fromSpinner);
			edit = (EditText) findViewById(R.id.fromEdit);
			result = (TextView) findViewById(R.id.resultText);
			loading = (ProgressBar) findViewById(R.id.progressBar1);
			loading.setVisibility(View.GONE);
			h = new Handler();
			
			spf = SAXParserFactory.newInstance();
			sp = spf.newSAXParser();
			xr = sp.getXMLReader();
			xr.setContentHandler(handler);
			
			ArrayAdapter adapterFrom = new ArrayAdapter<String>(getApplicationContext(),android.R.layout.simple_spinner_item, db.getAllCurrencies());
			from.setAdapter(adapterFrom);
			ArrayAdapter adapterTo = new ArrayAdapter<String>(getApplicationContext(),android.R.layout.simple_spinner_item, db.getAllCurrencies());
			to.setAdapter(adapterTo);
		} catch (Exception e) {

			e.printStackTrace();

		}
	}
	
	@Override
	public void onStart() {
		super.onStart();
		
		pref = getSharedPreferences("romaexchange", 0);
		from.setSelection(pref.getInt("selectedFrom", 0));
		to.setSelection(pref.getInt("selectedTo", 0));
		edit.setText(pref.getString("amount", ""));

		String previousDate = pref.getString("dataDate", "1900-01-01");
		String yesterday = df.format(new Date(new Date().getTime() - 86400000));
		
		Calendar cal = Calendar.getInstance();
		if( pref.getBoolean("online", true) ){
			if ( ((previousDate.compareTo(yesterday) < 0) && (cal.get(Calendar.DAY_OF_WEEK) != Calendar.SUNDAY)) ) {	
				task = new WorkerThread().execute("");
			}
		}else{
			notOnlineToast.show();
		}
	}

	@Override
	public void onStop() {
		super.onStop();
		pref = getSharedPreferences("romaexchange", 0);
		SharedPreferences.Editor editor = pref.edit();

		editor.putInt("selectedFrom", from.getSelectedItemPosition());
		editor.putInt("selectedTo", to.getSelectedItemPosition());
		editor.putString("amount", edit.getText().toString());
		editor.commit();
		
		if(task != null){
			task.cancel(true);
		}
	}



	public void calculate(View view) {
		int amount;
		// EditText edit = (EditText) findViewById(R.id.fromEdit);

		try {
			String amountS = edit.getText().toString();
			amount = Integer.parseInt(amountS);
			float rate = (db.getRate((String) to.getSelectedItem()) / db.getRate((String) from.getSelectedItem())) * amount;

			result.setText("" + String.format("%.2f", rate) + " " + ((String) to.getSelectedItem()));

		} catch (Exception e) {
			validNumber.show();
			// text1.setText(e.toString());
		}
	}

	
	public boolean onCreateOptionsMenu(Menu menu) {
    	menu.add(0, REFRESH, Menu.NONE, "Refresh exchange rates");
    	menu.add(0, SETTINGS, Menu.NONE, "Settings menu");
    	
    	return true;
    }

	public boolean onOptionsItemSelected(MenuItem item) {
    	super.onOptionsItemSelected(item);
    	
    	switch(item.getItemId()) {
    	case REFRESH:
    		pref = getSharedPreferences("romaexchange", 0);
    		
    		if(pref.getBoolean("online", true)){
    			task = new WorkerThread().execute("");
    		}else{
    			notOnlineToast.show();
    		}
    		return true;
    		
    	case SETTINGS:
    		Intent i = new Intent(Romaandroidlab1Activity.this, SettingsActivity.class);
    		startActivity(i);
    		return true;
    	}
    	return false; 
    }
	
	
	private void updateCurrency() {

		// TextView text1 = (TextView) findViewById(R.id.textView1);
		try {
			parseXML();
			storeData();
		} catch (Exception e) {
			
			unableToUpdateRatesToast.show();
			
			// text1.setText(e.toString());
		}

	}
	
	private void storeData() {
		for (Map.Entry<String, Float> entry : handler.getHashMap().entrySet()) {
			db.addOrUpdateCurrency(entry.getKey(), entry.getValue());
		}
		db.addOrUpdateCurrency("EUR", 1);
		
		pref = getSharedPreferences("romaexchange", 0);
		SharedPreferences.Editor editor = pref.edit();
		editor.putString("dataDate", handler.getDate());
		editor.commit();
	}

	private void parseXML() throws Exception {
		URL url = new URL(URLadress);

		xr.parse(new InputSource(url.openStream()));
	}
	
	
	private class WorkerThread extends AsyncTask<String, Void, String>{

		@Override
		protected void onPostExecute(String result) {
			Toast.makeText(getApplicationContext(), "Exchange rates are current as of " + handler.getDate() +".", Toast.LENGTH_LONG).show();
			h.post(new Runnable(){public void run() {loading.setVisibility(View.GONE);}});
		}

		
		@Override
		protected void onPreExecute() {
			//Toast toast = Toast.makeText(getApplicationContext(), "Exchange rates are refreshing",Toast.LENGTH_SHORT);
    		//toast.show();
			h.post(new Runnable(){public void run() {loading.setVisibility(View.VISIBLE);}});
		}


		@Override
		protected String doInBackground(String... params) {
			updateCurrency();
			return null;
		}
	
		
		
	}
}
